<?php

namespace App\Http\Controllers\Api;

use App\Repositories\Admin\HistoryRepository;
use App\Repositories\Admin\RankRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repositories\Admin\PictureRepository;
use Illuminate\Support\Facades\Redis;
use App\Repositories\Admin\UserRepository;
use App\Http\Controllers\Functions\ArrayFunctionsController as ArrayFunctions;

class MatchController extends Controller
{
    protected $pictureRepository;
    protected $historyRepository;
    protected $userRepository;
    protected $rankRepository;
    public function __construct(PictureRepository $pictureRepository)
    {
        $historyRepository = new HistoryRepository();
	$userRepository = new UserRepository();
        $rankRepository = new RankRepository();
        $this->historyRepository = $historyRepository;
        $this->pictureRepository = $pictureRepository;
        $this->rankRepository = $rankRepository;
	$this->userRepository = $userRepository;
    }
    public function getPictrue(Request $request){
        $oppenId = $request->get('oppenId');
        $userId = $request->get('userId');
        $pictureCategory = $request->get('pictureCategory');
        $pictureIds = $request->get('pictureIds');
        $pictureIds = json_decode($pictureIds,true);

        $oldPictureCategory = Redis::get('pictureCategory');
        if ($oldPictureCategory != $pictureCategory){
            if(Redis::get($oppenId))
                Redis::del($oppenId);
            Redis::set('pictureCategory', $pictureCategory);
        }

        if(!Redis::get($oppenId)) {
            $pictures = $this->getPictureFromDB($userId,$oppenId,$pictureCategory,$pictureIds);
            return json_encode(['code' => 200, 'pictures' => $pictures]);
        }else{
            $history = Redis::get($oppenId);
            $ids = unserialize($history);
            $pictures = [];
            $oldIds = $ids;
            if(count($ids) < 2){
                $pictures = $this->getPictureFromDB($userId,$oppenId,$pictureCategory,$pictureIds);
                return json_encode(['code' => 200, 'pictures' => $pictures,'pictureCategory'=>$pictureCategory]);
            }else {
                $keys = array_rand($ids, 2);
                $twoIds = [];
                $twoIds[] = $ids[$keys[0]];
                $twoIds[] = $ids[$keys[1]];
                unset($ids[$keys[0]]);
                unset($ids[$keys[1]]);
                Redis::set($oppenId, serialize($ids));
                $pictures = $this->pictureRepository->getMatchPicture($twoIds);
            }
            return json_encode(['code' => 200, 'pictures' => $pictures,'twoIds'=>$twoIds,'ids'=>$oldIds]);
        }

    }
    public function getPictureFromDB($userId,$oppenId,$pictureCategory,$pictureIdsFromXCX){

        //获取图片库里的所有图片id
        $pictures = $this->pictureRepository->getMatchAll($pictureCategory)->toArray();
        $pictureIds = array_column($pictures, 'picture_id');
        
	    //获取用户历史记录图片
        $histories = $this->historyRepository->getByUserId($userId)->toArray();
        $historyIds = array_merge(array_column($histories, 'history_picture_first_id'), array_column($histories, 'history_picture_second_id'));//两张图片的id

        $ids = array_diff($pictureIds, $historyIds); //可看图片id


	   if(count($ids)<2)  //可看图片少于两张则返回[]
            return [];

        $keys = array_rand($ids, 2);
        $twoIds = [];
//        return count($pictureIdsFromXCX);
        if(count($pictureIdsFromXCX) == 1){
            $twoIds[] = $pictureIdsFromXCX[0];
            if($ids[$keys[0]] == $pictureIdsFromXCX[0]) {
                $twoIds[] = $ids[$keys[1]];
                unset($ids[$keys[1]]);
            }else {
                $twoIds[] = $ids[$keys[0]];
                unset($ids[$keys[0]]);
            }
            $ids = ArrayFunctions::delArrayItemByValue($ids,$pictureIdsFromXCX[0]);
        }else if(count($pictureIdsFromXCX)== 2){
            $twoIds = $pictureIdsFromXCX;
            $ids = ArrayFunctions::delArrayItemByValue($ids,$pictureIdsFromXCX[0]);
            $ids = ArrayFunctions::delArrayItemByValue($ids,$pictureIdsFromXCX[1]);
        }else{
            $twoIds[] = $ids[$keys[0]];
            $twoIds[] = $ids[$keys[1]];
            unset($ids[$keys[0]]);
            unset($ids[$keys[1]]);

        }

        Redis::set($oppenId, serialize($ids));
        $pictures = $this->pictureRepository->getMatchPicture($twoIds);
        return $pictures;
    }

    /**
     * @param Request $request
     * @return string
     * 看图记录 升级
     */
    public function postPicture(Request $request){
        $user = $request->post('user');
        $choose_id = $request->post('choose_id');
        $pictures = $request->post('picturesId');
        $upPictures = $request->post('upPictures');
        $user_id = $user['user_id'];
//        图片
        $userLike = [
            'history_user_id' => $user_id,
            'history_choosed_picture_id' => $choose_id,
            'history_picture_first_id' => $pictures[0],
            'history_picture_second_id' => $pictures[1],
        ];
        //        区别出胜出图片和失败图片
        $winPicture = $upPictures[0];
        $defeatPicture = $upPictures[1];
        if($choose_id != $winPicture['picture_id']){
            $winPicture = $upPictures[1];
            $defeatPicture = $upPictures[0];
        }

        $addLineNumberStep = 1; //一次点赞增加的点赞数
        $likeNum = (int)$winPicture['picture_likenum'] + $addLineNumberStep;
        $picture_uprank_likenum = (int)$winPicture['picture_uprank_likenum'] + $addLineNumberStep;
        $pictureResult = $this->pictureRepository->updateLikenum($choose_id,$likeNum) ;//添加图片的点赞记录


        $disLikeId = $pictures[0];  //获取没有被点的图片的id

        if($choose_id == $pictures[0])
            $disLikeId = $pictures[1];

        $disLikePicture = $this->pictureRepository->getById($disLikeId);   //获取没有被点赞的次数
        $disLikeNum = (int)$disLikePicture['picture_dislikenum'] + 1;
        $pictureResult = $this->pictureRepository->updateDislikenum($disLikeId,$disLikeNum) ;//添加图片的不赞记录
        $picturesRankResult = $this->pictureUpRank($choose_id,$picture_uprank_likenum,$disLikeNum,$upPictures);
//        用户
        $result = $this->historyRepository->createHistory($userLike);//增加用户记录
	    //增加已用票数，减少总票数
        $addUsedTickeetNumber = 1;
        $user = $this->userRepository->getById($user_id);
        $usedTicket = $user['user_used_ticket'] + $addUsedTickeetNumber;//增加已用票
        $ticket = $user['user_ticket'] - $addUsedTickeetNumber;//减少可用票

//        $usedTicketResult = $this->userRepository->updateUsedTicket($user_id,$usedTicket);//增加已用票数
        $newRank = $this->userUpRank($user,$usedTicket,$ticket);//检查并更新等级
//        $TicketResult = $this->userRepository->updateTicket($user_id,$ticket);//减少可用票数
        return json_encode(['code'=>200,'history'=>$result->history_id,'newRank'=>$newRank,'ticket'=>$ticket]);
    }
    /**
     * 处理图片升级
     */
    public function pictureUpRank($choose_id,$picture_uprank_likenum,$disLikeNum,$upPictures){
//        区别出胜出图片和失败图片
        $winPicture = $upPictures[0];
        $defeatPicture = $upPictures[1];
        $isTopRank = false; //判断是否达到顶级
        if($choose_id != $winPicture['picture_id']){
            $winPicture = $upPictures[1];
            $defeatPicture = $upPictures[0];
        }
//        被点赞的图片处理是否升级
        if((int)$winPicture['picture_uprank_type'] == 1){
            $updatePictureData = [];
            if($picture_uprank_likenum > (int)$winPicture['picture_uprank_condition']){
                $rank = $this->rankRepository->getByTypeRankNumberStatus(2, $winPicture['picture_rank_number'] + 1, 1);
                $picture_uprank_likenum = $picture_uprank_likenum - $winPicture['picture_uprank_condition'];//升级后剩下的点赞数
                $nextRank = $this->rankRepository->getByTypeRankNumberStatus(2, $winPicture['picture_rank_number'] + 2, 1);

                $UprankTicketType = $nextRank->rank_condition_type;
                $Uprankcondition = $nextRank->rank_condition;
                $newPictureHealthPoint = (int)$winPicture['picture_health_point'] +  $rank->rank_health_point;
                $maxBlood =  Redis::get('maxBlood');
                if($newPictureHealthPoint > $maxBlood)
                    $newPictureHealthPoint = $maxBlood;
//                被点赞图片更新数据
                $updatePictureData = [
                    'picture_rank_number'  =>  (int)$winPicture['picture_rank_number'] + 1,
                    'picture_uprank_type'  =>  $UprankTicketType,
                    'picture_uprank_condition'  =>  $Uprankcondition,
                    'picture_uprank_likenum'  =>  $picture_uprank_likenum,
                    'picture_health_point'  =>  $newPictureHealthPoint//送血量
                ];

            }else{ //没有升级修改 picture_uprank_likenum 字段
                $updatePictureData = [
                    'picture_uprank_likenum'  =>  $picture_uprank_likenum,
                ];
            }
            $updateResult = $this->pictureRepository->updatePicture($winPicture['picture_id'],$updatePictureData);
            if(!$updateResult){
                //记录修改失败日志
            }
        }else{  //顶级
            $updatePictureData = [];
            if($picture_uprank_likenum > (int)$winPicture['user_uprank_ticket']) {
                $isTopRank = true;
            }else{
                $userUpdateData = [
                    'user_used_ticket' => $picture_uprank_likenum
                ];
            }
            $updateResult = $this->pictureRepository->updatePicture($winPicture['picture_id'],$updatePictureData);
        }

//        处理没被点赞图片的处理
        $reduceHealthPointStep = 1;
        $picture_health_point = $defeatPicture['picture_health_point'] - $reduceHealthPointStep; //减少血量
        $defeatPictureUpdateData = [
            'picture_health_point' => $picture_health_point,
        ];
        if($picture_health_point <= 0){
            $defeatPictureUpdateData = [
                'picture_health_point' => 0,
                'picture_status' => 2
            ];
        }
        $defeatUpdateResult = $this->pictureRepository->updatePicture($defeatPicture['picture_id'],$defeatPictureUpdateData);
        if(!$defeatUpdateResult){
            //记录修改失败日志
        }
}
    /**
     * 处理用户升级函数  百分比升级还未实现
     */
    public function userUpRank($user,$usedTicket,$ticket){
        $oldRankNumber = $user->user_rank_number;
        $newRankNumber = $oldRankNumber;
        $newRank = '';
        $userUprankTicketType = '';//下次升级等级类型
        $userUprankTicket = '';//下次升级所需票
        $userTicket = $ticket;
        $isTopRank = false; //判断是否达到顶级
        if((int)$user['user_uprank_type'] == 1){
            $userUpdateData = [];
            if($usedTicket > (int)$user['user_uprank_ticket']) {
                $rank = $this->rankRepository->getByTypeRankNumberStatus(1, $user['user_rank_number'] + 1, 1);
                $usedTicket = $usedTicket - $user['user_uprank_ticket'];
//                $usedTicketResult = $this->userRepository->updateUsedTicket($user['user_id'], $usedTicket);//更改已用票
                $nextRank = $this->rankRepository->getByTypeRankNumberStatus(1, $user['user_rank_number'] + 2, 1);
                $userUprankTicketType = $nextRank->rank_condition_type;
                $userUprankTicket = $nextRank->rank_condition;
                $newRank = $rank;
                $userTicket = $ticket + $rank->rank_health_point;

                /**
                 * 处理送道具 以后要在这里实现    $rank->rank_prop_id
                 */
                $userUpdateData = [
                    'user_rank_number' => $user['user_rank_number'] + 1,
                    'user_all_ticket' => $user['user_all_ticket'] + $rank->rank_health_point,
                    'user_ticket' => $userTicket,
                    'user_used_ticket' => $usedTicket,
                    'user_uprank_type' => $userUprankTicketType,
                    'user_uprank_ticket' => $userUprankTicket,
                ];
//                $this->userRepository->updateUserRankNumber($user['user_id'], $newRankNumber);//更改用户等级
            }else{
                $userUpdateData = [
                    'user_used_ticket' => $usedTicket,
                    'user_ticket' => $userTicket
                ];
            }
            $this->userRepository->updateUser($user['user_id'],$userUpdateData);
        }else { //顶级后
            $userUpdateData = [];
            if($usedTicket >= (int)$user['user_uprank_ticket']) {
                $rank = $this->rankRepository->getByTypeRankNumberStatus(1, $user['user_rank_number'] + 1, 1);
                $newRank = $rank;
                if($rank) {
                    $userUpdateData = [
                        'user_used_ticket' => $usedTicket,
                        'user_rank_number' => $user['user_rank_number'] + 1,
                        'user_all_ticket' => $user['user_all_ticket'] + $rank->rank_health_point,
                    ];
                    $this->userRepository->updateUser($user['user_id'], $userUpdateData);
                }
                $isTopRank = true;
            }else{
                $userUpdateData = [
                    'user_used_ticket' => $usedTicket,
                    'user_ticket' => $userTicket
                ];
                $this->userRepository->updateUser($user['user_id'],$userUpdateData);
            }

        }
        return ['rank'=>$newRank,'userUprankTicketType'=>$userUprankTicketType,'userUprankTicket'=>$userUprankTicket,'userTicket'=>$userTicket,'usedTicket'=>$usedTicket,'userinfo'=>$user,'isTopRank'=>$isTopRank];
    }

    /**
     * 用户退出某组时删除用户的可看图的id缓存
     */
    public function clearUserMatchRdis(Request $request){
        $oppenId = $request->get('oppenId');
        if(Redis::get($oppenId)) {
            Redis::del($oppenId);
            return json_encode(['code'=>200,'msg'=>'删除成功','pictureIds'=>Redis::get($oppenId)]);
        }else
            return json_encode(['code'=>200,'msg'=>'没有数据可删除']);
    }

}
